package com.second.app.forkjoin;

import java.net.ServerSocket;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @Author GYZ
 * @Date 2024/2/5
 * <pre>
 *  使用CustomRecursiveTask取得返回值与join和get方法区别
 *  主要体现在处理异常方面,使用get方法执行任务时，当子任务出现异常可以在main主线程中进行捕获
 * </pre>
 */

class GetRecursiveTask extends RecursiveTask<Integer> {
    @Override
    protected Integer compute() {
        System.out.println("Thread.currentThread.getName()" + "执行了compute方法");
        String nullString = null;
        nullString.toString();
        return 100;
    }
}

class JoinRun{
    public static void main(String[] args) {

            GetRecursiveTask getRecursiveTask = new GetRecursiveTask();
            ForkJoinPool pool = new ForkJoinPool();
            ForkJoinTask<Integer> task = pool.submit(getRecursiveTask);
            System.out.println(task.join());
            for (int i=0;i<Integer.MAX_VALUE;i++){
                String newString = new String();
                Math.random(); Math.random(); Math.random(); Math.random();
                Math.random(); Math.random(); Math.random(); Math.random();
            }
        System.out.println("main end");
    }
}
class GetRun{
    public static void main(String[] args) {
        try {
            GetRecursiveTask getRecursiveTask = new GetRecursiveTask();
            ForkJoinPool pool = new ForkJoinPool();
            ForkJoinTask<Integer> task = pool.submit(getRecursiveTask);
            System.out.println(task.get());
            for (int i=0;i<Integer.MAX_VALUE;i++){
                String newString = new String();
                Math.random(); Math.random(); Math.random(); Math.random();
                Math.random(); Math.random(); Math.random(); Math.random();
            }
        } catch (InterruptedException e) {
           e.printStackTrace();
            System.out.println("进入了mainA");
        } catch (ExecutionException e) {
            e.printStackTrace();
            System.out.println("进入了mainB");
        }
        System.out.println("main end");
    }
}

public class CustomRecursiveTask extends RecursiveTask<Integer> {
    @Override
    protected Integer compute() {
        System.out.println("compute time=" + System.currentTimeMillis());
        return 100;
    }
}

class Test1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CustomRecursiveTask customRecursiveTask = new CustomRecursiveTask();
        System.out.println(customRecursiveTask.hashCode());
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Integer> task = pool.submit(customRecursiveTask);
        System.out.println(task.hashCode() + " " + task.get());
        System.out.println(task.hashCode() + " " + task.join());
        Thread.sleep(5000);
    }
}
